/* 
    基础接口
*/

const baseRouter = require('koa-router')();

// 引入数据库查询方法
const query = require('../utils/mysql');
// 引入 sql语句
const {
    QUERY_USER_DETAIL,
    QUERY_USER_UID_BYUP,
    UPDATA_USER_PASSWORD_BYUID,
    QUERY_USER_PASSWORD_BYUID
} = require('../utils/sql');

// 查询用户详情接口
baseRouter.get('/getUserInfo', async (ctx) => {
    const request = ctx.request.query;
    const { uid } = request;
    const res = await query(QUERY_USER_DETAIL(uid));
    ctx.body = {
        flag: true,
        code: 1,
        data: {
            ...res[0]
        },
        msg: '查询成功'
    };
});

// 验证用户名和手机号是否匹配接口
baseRouter.post('/checkuser', async (ctx) => {
    const { _username, _phone } = ctx.request.body;
    // 根据用户名和手机号查询用户uid
    const res = await query(QUERY_USER_UID_BYUP(_username, _phone));
    if (!res.length) {
        ctx.body = {
            flag: false,
            code: -1,
            msg: '用户名或手机号码错误，请重新输入'
        };
        return;
    }
    ctx.body = {
        flag: true,
        code: 1,
        data: {
            uid: res[0].uid
        },
        msg: '查询成功'
    };
});

// 重置密码接口
baseRouter.post('/resetpassword', async (ctx) => {
    const { uid, password } = ctx.request.body;
    const res = await query(UPDATA_USER_PASSWORD_BYUID(uid, password));
    if (res) {
        ctx.body = {
            flag: true,
            code: 1,
            msg: '密码修改成功'
        };
    }
});

// 修改密码接口
baseRouter.post('/changepassword', async (ctx) => {
    const { uid, oldpassword, newpassword } = ctx.request.body;
    // 根据uid查询密码是否匹配，返回最终判断结果
    const res1 = await query(QUERY_USER_PASSWORD_BYUID(uid));
    const { password } = res1[0];
    if (password !== oldpassword) {
        ctx.body = {
            flag: false,
            code: -1,
            msg: '原始密码错误，请重新输入'
        };
        return false;
    }
    const res2 = await query(UPDATA_USER_PASSWORD_BYUID(uid, newpassword));
    if (res2) {
        ctx.body = {
            flag: true,
            code: 1,
            msg: '密码修改成功,请重新登录'
        };
    }
});



module.exports = baseRouter;